//
//  YHEmotionToolBar.swift
//  EmotionKeyboard
//
//  Created by 昱含 on 16/5/30.
//  Copyright © 2016年 YuHan. All rights reserved.
//

import UIKit

private let baseTag = 100
class YHEmotionToolBar: UIStackView {
    
    var selectedBtn: UIButton?
    var selectedBtnCallBack: ((index: Int) -> ())?
    
    init(){
        super.init(frame: CGRectZero)
        backgroundColor = UIColor.redColor()
        axis = .Horizontal
        distribution = .FillEqually
        setupUI()

    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        let packages = YHEmotionManager.sharedEmotion.packages
        for i in 0..<packages.count {
            let package = packages[i]
            var backImageName = "compose_emotion_table_mid"
            if i == 0 {
                backImageName = "compose_emotion_table_left"
            }else if i == packages.count - 1{
                backImageName = "compose_emotion_table_right"
            }
            addChildBtns(package.name!, backImageName: backImageName, index: i)
            
        }
    }
    
    @objc private func btnClick(btn: UIButton) {
        selectedBtn?.selected = false
        btn.selected = true
        selectedBtn = btn
        selectedBtnCallBack?(index: btn.tag - baseTag)
    }
    
    func setSelectBtn(section: Int){
        let btnTag = baseTag + section 
        let btn = self.viewWithTag(btnTag) as! UIButton
        selectedBtn?.selected = false
        btn.selected = true
        selectedBtn = btn
        
    }
    
    private func addChildBtns(title: String, backImageName: String, index: Int){
        let btn = UIButton()
        btn.tag = index + baseTag
        btn.setTitle(title, forState: .Normal)
        btn.setBackgroundImage(UIImage(named: backImageName + "_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: backImageName + "_selected"), forState: .Selected)
//        btn.titleLabel?.font = UIFont.systemFontOfSize(<#T##fontSize: CGFloat##CGFloat#>)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        btn.addTarget(self, action: #selector(YHEmotionToolBar.btnClick(_:)), forControlEvents: .TouchUpInside)
        addArrangedSubview(btn)
        if index == 0 {
            btn.selected = true
            selectedBtn = btn
        }
        
    }

}
